<?php
namespace app\index\controller\clinic;
use app\index\controller\BaseIndex;
use app\common\model\ClinicAdmin;
use app\common\model\Clinic;
use app\common\model\AuthRule;
use app\common\model\ClinicAuthGroup;
use szktor\SystemDict; //系统字典
use szktor\ClinicDict; //诊所门店公共字典

/*
* 前台-门店人员 角色 设置
*/
class AdminGroup extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = [];  //无需鉴权的方法，但需要登录

    //初始化
    public function initialize()
    {
        parent::initialize();
    }
    
    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            $data = $this->request->only(['keyword','status','page'],'post');
            //条件
            $map = [['clinic_id','=', $this->admin['clinic_id']],['is_del','=','0']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|remark','like','%' . $data['keyword'] . '%'];
            }
            if(strtoupper($data['status']) != 'ALL')
            {
                $map[] = ['status','=',(int)$data['status']];
            }
            $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
            $list = ClinicAuthGroup::where($map)->field('*')
                    ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            if (count($list) <= 0) {
                return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
            }
            $res = ['code' => 0, 'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
            foreach ($res['data'] as $key => &$val) {
                $val['supper_name'] = '/';
                if((int)$val['is_supper_admin'] > 0) //超级管理角色
                {
                    $val['supper_name'] = '超级管理角色';
                }
            }
            return json($res);
        }
        return $this->view->fetch();
    }
    //添加+修改
    public function info($id = 0)
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            $data = $this->request->only(['group_id','user_name','open','sex','id','remark','index_page','rules'],'post');
            if(isset($data['open'])) $data['open'] = $data['open'] == 'on' ? '1' : '0';
            try
            {
                if(isset($data['rules']))
                {
                    $data['rules'] = empty($data['rules']) ? '*' : trim($data['rules']);
                }else{
                    $data['rules'] = '*';
                }
                $now_time = time();
                $info = ClinicAuthGroup::where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id'],'is_del' => '0'])->find();
                $sqlData = [
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'pid' => (int)$data['group_id'], //权限级id
                    'name' => $data['user_name'], //名称
                    'rules' => $data['rules'], //规则ID
                    'status' => isset($data['open']) ? (int)$data['open'] : '0', //状态0=停用,1=正常
                    'create_time' => $now_time, //创建时间
                    'update_time' => $now_time, //更新时间
                    'remark' => $data['remark'], //角色组操作信息备注
                    'index_page' => $data['index_page'], //工作首页
                ];
                if($info) //信息已存在
                {
                    unset($sqlData['clinic_id'],$sqlData['create_time']);
                    if((int)$info['is_supper_admin'] > 0) //超级管理员
                    {
                        unset($sqlData['pid'],$sqlData['rules'],$sqlData['status'],$sqlData['index_page']);
                    }
                    $editRes = ClinicAuthGroup::where(['id' => $info['id']])->update($sqlData);
                }else{ //信息不存在
                    $editRes = ClinicAuthGroup::insertGetId($sqlData);
                }
                if(!$editRes) return json(['err' => '5', 'msg' => '角色信息保存失败']);
                return json(['err' => '0', 'msg' => '角色信息已保存成功']);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '6', 'msg' => '失败：' . $e->getMessage()]);
            }
        }
        $info = ClinicAuthGroup::where(['id' => (int)$id, 'clinic_id' => $this->admin['clinic_id'],'is_del' => '0'])->find();
        $this->assign([
            'info' => $info,
            'page_title' => !$info ? '添加' : '修改',
            'group_list' => ClinicAuthGroup::getGroupList($this->admin['clinic_id'],true),
            'work_page_list' => ClinicDict::getWorkspacePageList(), //工作台
            'rule_list' => AuthRule::getIndexGroupSetRuleList($this->clinic,$info), //权限设置
        ]);
        return $this->view->fetch();
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        $data = $this->request->only(['id']);
        if(intval($data['id']) <= 0){
            return json(['err' => '2', 'msg' => '参数错误，请重试']);
        }
        //条件
        $map = [['id','in',$data['id']],['is_supper_admin','=','0'],['clinic_id','=',$this->admin['clinic_id']]];
        $r = ClinicAuthGroup::where($map)->update(['is_del' => '1']);
        if(!$r) return json(['err' => '3', 'msg' => '删除失败，请重试']);
        return json(['err' => '0', 'msg' => '删除成功']);
    }
}
